package com.acmelabs.inbox;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NotificationInboxReceiver extends BroadcastReceiver {

	ArrayList<Notification> notiArray;
	FileInputStream fis;
	NotificationIO io = new NotificationIO();

	@Override
	public void onReceive(Context context, Intent intent) {

		writeNotificationListToFile(context, intent);
	}

	void loadNotifcationListFromFile(Context context) {

		NotificationIO io = new NotificationIO();
		
		if (io.read(context)) {
			notiArray = io.getNotificationList();
		} else {
			notiArray = new ArrayList<Notification>();
		}

	}

	void writeNotificationListToFile(Context context, Intent intent) {
		
		loadNotifcationListFromFile(context);
		
		try {
			Notification notif = new Notification();
			notif = setNotification(notif, intent);
			notiArray.add(notif);
			FileOutputStream fos;
			fos = context.openFileOutput("ACME_LABS", Context.MODE_PRIVATE);
			io.write(notiArray, fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	Notification setNotification(Notification noti, Intent intent) {
		noti
				.setDateAndTime(DateFormat.getDateTimeInstance().format(
						new Date()));
		noti.setTitle(intent.getStringExtra("NOTIFICATION_TITLE"));
		noti.setDetails(intent.getStringExtra("NOTIFICATION_DETAILS"));
		noti.setUrl(intent.getStringExtra("NOTIFICATION_URL"));
		noti.setActionName(intent.getStringExtra("NOTIFICATION_ACTION_NAME"));
		noti.setActionCategories(intent
				.getStringExtra("NOTIFICATION_ACTION_CATEGORIES"));
		noti.setUrl(intent.getStringExtra("NOTIFICATION_URL"));
		noti.setID(intent.getStringExtra("NOTIFICATION_CP_ID"));
		noti.setTicker(intent.getStringExtra("NOTIFICATION_TICKER"));
		noti.setActionComponent(intent
				.getStringExtra("NOTIFICATION_ACTION_COMPONENT"));
		noti.setActionLable(intent.getStringExtra("NOTIFICATION_ACTION_LABEL"));
		noti.setActionName(intent.getStringExtra("NOTIFICATION_ACTION_NAME"));
		noti.setActionCategories(intent
				.getStringExtra("NOTIFICATION_ACTION_CATEGORIES"));
		noti.setActionData(intent.getStringExtra("NOTIFICATION_ACTION_DATA"));
		try {
			noti.setShowThumbs(Boolean.parseBoolean(intent.getStringExtra("NOTIFICATION_SHOW_THUMBS")));
		} catch (Exception e) {
			noti.setShowThumbs(false);
		}
		try {
			noti.setLocationLatitude(Double.parseDouble(intent
					.getStringExtra("NOTIFICATION_LOCATION_LATITUDE")));
		} catch (Exception e) {
			noti.setLocationLatitude(0);
		}
		try {
			noti.setLocationLongitude(Double.parseDouble(intent
					.getStringExtra("NOTIFICATION_LOCATION_LONGITUDE")));
		} catch (Exception e) {
			noti.setLocationLatitude(0);
		}

		return noti;
	}

}